const request = require('../../utils/request');
const buildUrl = request.buildUrl || ((url) => url);

Page({
  data: {
    typeOptions: ['功能问题', '界面问题', '体验建议', '其他'],
    typeIndex: 0,
    content: '',
    contact: '',
    submitting: false
  },

  onLoad() {
    wx.setNavigationBarTitle({ title: '意见反馈' });
  },

  onTypeChange(e) {
    this.setData({ typeIndex: Number(e.detail.value) || 0 });
  },

  onContentInput(e) {
    this.setData({ content: e.detail.value || '' });
  },

  onContactInput(e) {
    this.setData({ contact: e.detail.value || '' });
  },

  get canSubmit() {
    return (this.data.content || '').trim().length >= 5;
  },

  submitFeedback() {
    if (this.data.submitting) return;

    const content = (this.data.content || '').trim();
    if (content.length < 5) {
      wx.showToast({ title: '请至少填写5个字的反馈内容', icon: 'none' });
      return;
    }

    const app = getApp();
    const userId = app.globalData.userId || wx.getStorageSync('userId') || null;

    this.setData({ submitting: true });

    wx.request({
      url: buildUrl('/api/feedback'),
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token') || ''}`
      },
      data: {
        userId,
        userType: 'order_user',
        content,
        contact: this.data.contact || ''
      },
      success: (res) => {
        const data = res.data || {};
        if (data.success) {
          wx.showToast({ title: '提交成功，感谢反馈', icon: 'success' });
          this.setData({
            typeIndex: 0,
            content: '',
            contact: ''
          });
          setTimeout(() => {
            wx.navigateBack({ delta: 1 });
          }, 800);
        } else {
          wx.showToast({ title: data.message || '提交失败，请稍后再试', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
      },
      complete: () => {
        this.setData({ submitting: false });
      }
    });
  }
});
